Classes in JavaScript are a blueprint for creating objects. They encapsulate data and behavior by defining properties and methods, enabling object-oriented programming. Classes were introduced in ECMAScript 2015 (ES6).
You can define a class using the class
keyword:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
}
const person1 = new Person("Alice", 30);
console.log(person1.greet()); // Hello, my name is Alice and I am 30 years old.
Classes can also be defined using class expressions:
const Person = class {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
};
const person2 = new Person("Bob", 25);
console.log(person2.greet()); // Hello, my name is Bob and I am 25 years old.
Classes can inherit from other classes using the extends
keyword:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a noise.`;
}
}
class Dog extends Animal {
speak() {
return `${this.name} barks.`;
}
}
const dog = new Dog("Rex");
console.log(dog.speak()); // Rex barks.
Static methods are defined on the class itself, not on instances of the class:
class MathUtil {
static add(a, b) {
return a + b;
}
}
console.log(MathUtil.add(5, 3)); // 8
Getters and setters allow you to define methods that get and set the value of an object's properties:
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
get area() {
return this.width * this.height;
}
set area(value) {
this.width = Math.sqrt(value);
this.height = Math.sqrt(value);
}
}
const rect = new Rectangle(4, 5);
console.log(rect.area); // 20
rect.area = 25;
console.log(rect.width); // 5
console.log(rect.height); // 5
For more detailed information, you can check out resources like MDN Web Docs[^1^][2] and W3Schools[^2^][1].